<?php


namespace app\zftpay\controller;


use app\service\appletService;
use app\service\propertyService;
use app\service\xcxService;
use app\zftpay\controller\AlipayAuth;
use app\service\webService;
use app\zftpay\service\apiService;
use think\Controller;
use think\Db;
use think\Log;


//class Index extends Controller
class Index extends AlipayAuth
{
    public function selectroom(){
        //session("url",request()->url());
        /*$roominfo_user=Db::table("roominfo_user")->where("user_id",session('user_id'))->find();
        if(!empty($roominfo_user))
        {
            $url=url("H5alipay/billinfo_discount")."?id=".$roominfo_user["room_id"];
            echo "<script>location.href='$url';</script>";
            exit;
        }*/
        $community_id=request()->get("community_id");
        $communityinfo=Db::table("community")->where("id",$community_id)->find();
        if(empty($communityinfo)){
            return "小区信息错误";
            $this->error("小区信息错误");
        }
        $this->assign("communityinfo",$communityinfo);

        $group = (new xcxService())->groupList($communityinfo["community_id"]);

        $str="[";
        foreach ($group as $key => $value) {
            $str=$str."'".$value."',";
        }
        $str=$str."]";

        $this->assign("str",$str);
        return $this->fetch();
    }

    public function checkname(){
        if(request()->isPost())
        {
            $data=request()->post();
            $roominfo=Db::table("roominfo")->where("id",$data["room_id"])->find();

            if(strpos($roominfo["owner_name"],$data["owner_name"])!== false){
                $roominfo_user=Db::table("roominfo_user")->where("user_id",session("user_id"))->where("room_id",$data["room_id"])->find();
                /*$url=url("billinfo_discount")."?id=".$roominfo["id"];
                echo "<script>location.href='$url';</script>";
                exit;*/
                if(empty($roominfo_user))
                {
                    $communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
                    $info["user_id"]=session("user_id");
                    $info["room_id"]=$data["room_id"];
                    $info["community_id"]=$roominfo["community_id"];
                    $info["community_name"]=$communityinfo["community_name"];
                    $info["address"]=$roominfo["address"];
                    $info["create_time"]=time();
                    $res=Db::table("roominfo_user")->insert($info);
                }
                $url=url("billinfo")."?id=".$roominfo["id"];
                echo "<script>location.href='$url';</script>";
                exit;

            }else{
                echo "<script>alert('验证失败');history.go(-1);</script>";
                exit;
            }
        }else{
            $id=request()->get("id");
            $url=url("billinfo")."?id=".$id;
            echo "<script>location.href='$url';</script>";
            exit;
            $roominfo_user=Db::table("roominfo_user")->where("user_id",session("user_id"))->where("room_id",$id)->find();
            if(!empty($roominfo_user)){
                $url=url("billinfo")."?id=".$id;
                echo "<script>location.href='$url';</script>";
                exit;
            }
            $roominfo=Db::table("roominfo")->where("id",$id)->find();
            if(mb_strlen($roominfo["owner_name"])=="1"){
                $url=url("billinfo")."?id=".$roominfo["id"];
                echo "<script>location.href='$url';</script>";
                exit;
            }
            if(empty($roominfo["owner_name"])){
                $url=url("billinfo")."?id=".$roominfo["id"];
                echo "<script>location.href='$url';</script>";
                exit;
            }
            $roominfo["owner_name"]=str_repeat('*', mb_strlen($roominfo['owner_name'])-1).mb_substr($roominfo["owner_name"],-1);
            $this->assign("roominfo",$roominfo);
            return $this->fetch("check_name");
        }

    }

    public function billinfo(){
        session("url",request()->url());
        $id=request()->get("id");
        $roominfo=Db::table("roominfo")->where("id",$id)->find();
        $communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();

        $roominfo["community_name"]=$communityinfo["community_name"];

        //根据房号查询账单
        $billlis = (new appletService())->billRoomIdList($roominfo['out_room_id']);
        if(empty($billlis)){
            return $this->fetch("nopaymsg");
        }
        //查询缴费类型
        $costtype = (new appletService())->cost_type($roominfo['out_room_id']);
        $billsum=(new appletService())->billsum($roominfo['out_room_id']);
        $billlist=array();
        foreach ($costtype as $b){
            $arr["costtype"]=$b;
            $billinfo = (new appletService())->cost_type_bill($roominfo['out_room_id'],$b);
            $arr["billinfo"]=$billinfo;
            $billlist[]=$arr;
        }

        /*echo "<pre>";
        var_dump($billlist);
        die;*/
        $this->assign("billsum",$billsum);
        $this->assign("billlist",$billlist);
        $this->assign("roominfo",$roominfo);

        $notifyurl_alipay=(new webService())->getNotifyurlAlipay();
        $this->assign("notifyurl_alipay",$notifyurl_alipay);
        return $this->fetch();
    }

    public function createOrder(){
        if(!(request()->has('billid'))){
            return json(['info' => '请选择要交费的账单']);
        }
        $post=request()->post();
        $billpay["billid"]=serialize($post["billid"]);

        $ordermoney=0;
        $subjectremark="";
        foreach ($post["billid"] as $key => $value) {
            $billinfo=Db::table("bill")->where('id',$value)->find();
            if($billinfo["status"]=="TRADE_SUCCESS"){
                return json(['info' => '该帐单已缴费']);
            }
            $ordermoney=$ordermoney+$billinfo["bill_entry_amount"];

            $subjectremark=$subjectremark.$billinfo["cost_type"].":".$billinfo["bill_entry_amount"]."元| ";
        }
        $billpay["order_money"]=$ordermoney;
        $billpay["user_id"]=session("user_id");

        $billpay["out_room_id"]=$post["out_room_id"];
        $billpay["room_address"]=$post["room_address"];
        $billpay["community_id"]=$post["community_id"];
        $billpay["community_name"]=$post["community_name"];

        $billpay["pay_money"]=round($billpay["order_money"],2);
        $billpay["out_trade_no"]=date('YmdHiss').rand(100000,999999);


        $propertyZftInfo=(new propertyService())->propertyZftByCommunityId($post["community_id"]);
        if(empty($propertyZftInfo)){
            return json(['info' => '直付通配置为空']);
        }
        $subject = $billpay["community_name"].$billpay["room_address"].$subjectremark.'已缴费';
        $api = new apiService();



        $notifyUrl="https://www.wuye.zfbzhsq.com/admin/callback/alinotice";

        $settle_detail_info=array(
            'trans_in_type'=>'defaultSettle',//'loginName',
            'trans_in'=>'',//收款账号aliwykd@163.com
            'amount'=>$billpay["pay_money"],//结算金额
        );
        $data= array(
            'out_trade_no'=> $billpay["out_trade_no"],
            'total_amount'=>$billpay["pay_money"],
            'buyer_id'=>$billpay["user_id"],//$info["user_id"],
            'subject' =>$subject,
            'merchant_id'=>$propertyZftInfo["merchant_id"],
            'notifyUrl'=>$notifyUrl,
            'settle_detail_info'=>$settle_detail_info,
        );
        $result = $api->create(json_encode($data));

        if(property_exists($result,'sub_msg')){
            return json(['info' => $result->sub_msg]);
        }else{
            $billpay['trade_no'] =  $result->trade_no;

            $billpay["scenes"]=5;
            $billpay["subject"]=$subject;
            $res=Db::table("billpay")->insert($billpay);
            //返回结果到前台唤起收银台
            if($res){
                return json(['order_no' => $billpay['trade_no']]);
            }else{
                return json(['info' => '订单存储失败']);
            }
        }
    }
    public function index(){
        $notifyurl_alipay=(new webService())->getNotifyurlAlipay();
        $this->assign("notifyurl_alipay",$notifyurl_alipay);
        return $this->fetch("pay");
    }
    public function index2(){
        $notifyurl_alipay=(new webService())->getNotifyurlAlipay();
        $this->assign("notifyurl_alipay",$notifyurl_alipay);
        return $this->fetch("pay2");
    }

    //直付通收款
    public function pay(){
        $gateid=1;
        $gateinfo=Db::table("property_parking_gate")->where("id",$gateid)->find();


        $info["property_id"]=1;


        $info["order_money"]=request()->post("pay_money");
        $info["remark"]=request()->post("remark");
        $info["user_id"]=session("user_id");
        //$info["user_id"]="2088222524772492";
        $info["community_name"]="早早测试";
        $info["pay_money"]=request()->post("pay_money");
        $info["out_trade_no"]=date('YmdHiss').rand(100000,999999);
        $info["subject"] = $gateinfo["community_name"]."-".$gateinfo["gateName"];

        $propertyinfo= Db::name('property')->where('id',$gateinfo["property_id"])->find();
        $token=$propertyinfo["parking_accredit"];
        $api = new apiService();

        $notifyUrl="https://www.wuye.zfbzhsq.com/zftpay/callback/notice";
        $serviceinfo=Db::table("service")->where("id",$propertyinfo["service_id"])->find();

        $settle_detail_info=array(
            'trans_in_type'=>'defaultSettle',//'loginName',
            'trans_in'=>'',//收款账号aliwykd@163.com
            'amount'=>$info["pay_money"],//结算金额
        );
        $data= array(
            'out_trade_no'=> $info["out_trade_no"],
            'total_amount'=>$info["pay_money"],
            'buyer_id'=>$info["user_id"],//$info["user_id"],
            'subject' =>$info["subject"],
            'notifyurl'=>$notifyUrl,
            'sell_id'=>'2088610148420721',
            'notifyUrl'=>$notifyUrl,
            'settle_detail_info'=>$settle_detail_info,
            );
        $result = $api->create(json_encode($data));

        Log::write($result);
        if(property_exists($result,'sub_msg')){
            return json(['info' => $result->sub_msg]);
        }else{

            $info['trade_no'] =  $result->trade_no;
            $res=Db::table("zft_order")->insert($info);
            //返回结果到前台唤起收银台
            if($res){
                return json(['order_no' => $info['trade_no']]);
            }else{
                return json(['info' => '订单存储失败']);
            }
        }
    }

    //直付通银行收款
    public function pay2(){
        $gateid=1;
        $gateinfo=Db::table("property_parking_gate")->where("id",$gateid)->find();


        $info["property_id"]=1;


        $info["order_money"]=request()->post("pay_money");
        $info["remark"]=request()->post("remark");
        $info["user_id"]=session("user_id");
        //$info["user_id"]="2088222524772492";
        $info["community_name"]="早早测试";
        $info["pay_money"]=request()->post("pay_money");
        $info["out_trade_no"]=date('YmdHiss').rand(100000,999999);
        $info["subject"] = $gateinfo["community_name"]."-".$gateinfo["gateName"];

        $propertyinfo= Db::name('property')->where('id',$gateinfo["property_id"])->find();
        $token=$propertyinfo["parking_accredit"];
        $api = new apiService();

        $notifyUrl="https://www.wuye.zfbzhsq.com/zftpay/callback/notice";
        $serviceinfo=Db::table("service")->where("id",$propertyinfo["service_id"])->find();

        $settle_detail_info=array(
            'trans_in_type'=>'cardAliasNo',//'loginName',
            'trans_in'=>'081a3ab713395cc',//收款账号aliwykd@163.com1202225909100018657  081a3ab713395cc
            'amount'=>$info["pay_money"],//结算金额
        );
        $data= array(
            'out_trade_no'=> $info["out_trade_no"],
            'total_amount'=>$info["pay_money"],
            'buyer_id'=>$info["user_id"],//$info["user_id"],
            'subject' =>$info["subject"],
            'notifyurl'=>$notifyUrl,
            'sell_id'=>'2088610148420721',
            'notifyUrl'=>$notifyUrl,
            'settle_detail_info'=>$settle_detail_info,
        );
        $result = $api->create2(json_encode($data));

        Log::write($result);
        if(property_exists($result,'sub_msg')){
            return json(['info' => $result->sub_msg]);
        }else{

            $info['trade_no'] =  $result->trade_no;
            $res=Db::table("zft_order")->insert($info);
            //返回结果到前台唤起收银台
            if($res){
                return json(['order_no' => $info['trade_no']]);
            }else{
                return json(['info' => '订单存储失败']);
            }
        }
    }

}